<?php

namespace Blog\App\Model;

use HX\App;
use Hx\Request;

/**
 * 评论操作类
 * Class Comment
 * @package Blog\App\Model
 */
class Comment {

    /**
     * 数据库对象
     * @var \Hx\Db
     */
    private $db;

    /**
     * 构造函数
     */
    public function __construct() {
        $this->db = App::Db();
    }

    /**
     * 获取树状评论
     * @param int $node 文章id
     * @return array|mixed
     */
    public function getTree($node) {
        $col = 'id,author,email,url,createDate,content,parentId,';
        $col .= 'status,userIp,userAgent';
        $sql = App::Sql('HxSite_Comment', $col)
            ->where('nodeId = :node AND commentType = "comment" AND status = "public"')
            ->order('id ASC')
            ->select();
        $commentData = $this->db->queryAll($sql, array('node' => $node));
        if ($commentData) {
            $tempData = array();
            foreach ($commentData as $c) {
                $c->avatar = $this->getAvatar($c->email);
                unset($c->email);
                $tempData[$c->id] = $c;
            }
            $commentData = array();
            foreach ($tempData as $k => $c) {
                if ($tempData[$c->parentId]) {
                    #将子评论移动到父评论麾下
                    $tempData[$c->parentId]->children[] =& $tempData[$k];
                    continue;
                }
                if ($c->parentId > 0) {
                    continue;
                }
                $commentData[] =& $tempData[$k];
            }
        }
        return $commentData;
    }

    /**
     * 添加评论
     * @param array $data
     * @return bool|mixed
     */
    public function addComment($data) {
        $data['content'] = $this->formatContent($data['content']);
        if (strlen($data['content']) < 3) {
            return false;
        }
        $col = 'author,email,url,createDate,content,userId,nodeId,parentId,';
        $col .= 'commentType,status,userIp,userAgent';
        $sql = App::Sql('HxSite_Comment', $col)
            ->insert();
        $this->db->exec($sql, array(
            'author' => $data['author'],
            'email' => $data['email'],
            'url' => $data['url'],
            'content' => $data['content'],
            'createDate' => time(),
            'userId' => 0,
            'nodeId' => $data['node'],
            'parentId' => $data['parentId'],
            'commentType' => 'comment',
            'status' => $this->checkEmail($data['email']) ? 'public' : 'check',
            'userIp' => Request::$ip,
            'userAgent' => Request::$agent
        ));
        return $this->getOne($this->db->lastId());
    }

    /**
     * 检测email是否通过
     * @param string $email
     * @return bool
     */
    private function checkEmail($email) {
        $sql = App::Sql('HxSite_Comment', 'id')
            ->where('email = :email AND status = "public" AND commentType = "comment"')
            ->select();
        $data = $this->db->query($sql, array('email' => $email));
        if (!$data) {
            return false;
        }
        return $data->id > 0;
    }

    /**
     * 获取一个评论
     * @param int $id 评论id
     * @return bool|mixed
     */
    private function getOne($id) {
        $col = 'id,author,email,url,createDate,content,parentId,';
        $col .= 'status,userIp,userAgent';
        $sql = App::Sql('HxSite_Comment', $col)
            ->where('id = :id')
            ->select();
        $data = $this->db->query($sql, array('id' => $id));
        if (!$data) {
            return false;
        }
        $data->avatar = $this->getAvatar($data->email);
        unset($data->email);
        return $data;
    }

    /**
     * 获取Gravatar头像
     * @param string $email
     * @return string
     */
    private function getAvatar($email) {
        return 'http://1.gravatar.com/avatar/' . md5($email) . '?s=40&r=G&d=http://ww1.sinaimg' .
            '.cn/large/67252e9ajw1dqn0haiinwj' .
            '.jpg';
    }

    /**
     * 处理评论内容
     * @param string $content
     * @return string
     */
    private function formatContent($content) {
        $content = htmlspecialchars($content, ENT_QUOTES);
        $content = nl2br($content, true);
        return $content;
    }

    /**
     * 获取最新的评论
     * @param int $size
     * @return mixed
     */
    public function getNew($size = 3) {
        $col = 'Comment.id AS id,Comment.author AS author,Comment.content AS content,';
        $col .= 'Node.nodeKey AS nodeKey';
        $sql = App::Sql('HxSite_Comment AS Comment', $col)
            ->leftJoin('HxSite_Node AS Node', 'Node.id = Comment.nodeId')
            ->order('Comment.createDate DESC')
            ->where('Comment.commentType = "comment" AND Comment.status = "public" AND Comment.parentId = 0')
            ->limit($size)
            ->select();
        return $this->db->queryAll($sql);
    }
}